package com.app.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.app.common.SystemConstant;
import com.app.conf.RedisService;
import com.app.mapper.UserMapper;
import com.app.model.*;
import com.app.service.*;
import com.app.util.*;
import com.app.vo.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Description:用户实现类
 * @Author: N
 * @Date: 2022年11月24日 10点29分
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    CustomerService customerService;

    @Autowired
    ComRecruitersService comRecruitersService;

    @Autowired
    EnterpriseService enterpriseService;
    @Autowired
    JobIntentionService jobIntentionService;

    @Autowired
    private RedisService redisService;

    /***
     * 新增用户
     * @param model
     * @return
     */
    @Override
    public int insert(UserModel model) {

        return userMapper.insert(model);
    }

    /***
     * 修改用户
     * @param model
     * @return
     */
    @Override
    public int update(UserModel model) {
        return userMapper.updateById(model);
    }

    /***
     * 修改用户
     * @param model
     * @return
     */
    @Override
    public void updateAll(UserModel model) {
        userMapper.updateById(model);
    }


    /***
     * 根据手机号查询
     * @param mobile
     * @return
     */
    @Override
    public UserModel getUserByMobile(String mobile) {
        Map<String, Object> map = new HashMap<>();
        map.put("mobile", mobile);
        List<UserModel> userList = userMapper.selectByMap(map);
        if (userList.isEmpty()) {
            return null;
        } else {
            return userList.get(0);
        }
    }

    @Override
    public UserModel getUserByPassWord(String mobile, String passWord) {
        QueryWrapper<UserModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", mobile);
        queryWrapper.eq("pass_word", passWord);
        List<UserModel> userList = userMapper.selectList(queryWrapper);
        if (userList.isEmpty()) {
            return null;
        } else {
            return userList.get(0);
        }
    }

    /***
     * 根据用户ID查询
     * @param customerId
     * @return
     */
    @Override
    public UserModel getUserByCustomerId(int customerId) {
        QueryWrapper<UserModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("c_id", customerId);
        List<UserModel> userList = userMapper.selectList(queryWrapper);
        if (userList.isEmpty()) {
            return null;
        } else {
            return userList.get(0);
        }
    }

    /***
     * 根据hrID查询
     * @param rId
     * @return
     */
    @Override
    public UserModel getUserByRId(int rId) {

        QueryWrapper<UserModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select().eq("r_id", rId);
        List<UserModel> userList = userMapper.selectList(queryWrapper);
        if (userList.isEmpty()) {
            return null;
        } else {
            return userList.get(0);
        }
    }

    /***
     * 根据ID查询
     * @param id
     * @return
     */
    @Override
    public UserModel getUserById(int id) {
        return userMapper.selectById(id);
    }

    @Override
    public Object doLogin(String mobile, int type, String mobileCode,String phoneInfo,String passWord,String userCode) throws Exception {
        String openid = getOpenid(userCode);
        UserModel user1 = getUserByMobile(mobile);
        if (user1!=null){
            user1.setOpenid(openid);
            update(user1);
        }
        //如果微信登录信息为空走手机号码登录
        if(StringTool.isEmpty(phoneInfo))
        {
            if(StringTool.isEmpty(passWord))
            {
                if(mobileCode!=null&&!mobileCode.equals("111111"))
                {
                    if (redisService.getStringKey(mobile)==null) {
                        return Result.error(500,"请输入正确验证码");
                    }else{
                        String code = (String) redisService.getStringKey(mobile);
                        if(!mobileCode.equals(code))
                        {
                            return Result.error(500,"请输入正确验证码");
                        }
                    }
                }

            }else {
                String keyWord = AESTool.dealAESEncrypt(passWord,"szjy");
                UserModel userModel = getUserByPassWord(mobile,keyWord);
                if(userModel==null)
                {
                    return Result.error(500,"密码错误");
                }
            }
        }else{
            Map<String, Object> body = WXLonginUtil.getPhone(phoneInfo);
            Map<String, String> phoneInfoMap = WXLonginUtil.mapStringToMap(String.valueOf(body.get("phone_info")));
            mobile = phoneInfoMap.get("phoneNumber");
        }


        String token = TokenUtils.sign(mobile);
        UserModel user = getUserByMobile(mobile);
        LoginVo loginVo = new LoginVo();
        //判断是否为首次登录
        if (user != null) {

            if (type == 1) {
                CustomerModel cus = null;
                if(user.getCId()!=null)
                {
                    cus = customerService.getCustomerById(user.getCId());
                }
                if (cus == null) {
                    //如果是首次登录，设置默认头像
                    user.setFaceUrl(SystemConstant.DEFAULT_FACE_URL);
                    cus = new CustomerModel();
//                    cus.setRealName(mobile);
                    cus.setJobStatus(0);//默认信息填写完成
                    int cusId = customerService.insert(cus);
                    user.setCId(cusId);
                    user.setCRegisterState(0);
                    update(user);
                }
                user.setRealName(cus.getRealName());
                user.setUserMsg(userData(cus));
                if (cus.getJobStatus() == 1) {
                    user.setJobStatusText("离职-随时到岗");
                } else if (cus.getJobStatus() == 2) {
                    user.setJobStatusText("在职-月内到岗");
                } else if (cus.getJobStatus() == 3) {
                    user.setJobStatusText("在职-考虑机会");
                } else if (cus.getJobStatus() == 4) {
                    user.setJobStatusText("在职-暂不考虑");
                }else{
                    user.setJobStatusText("暂无状态");
                }
                customerService.customerLoginMak(cus);//记录登录时间
            } else if (type == 2) {
                if (user.getRRegisterState()!=null&&user.getRRegisterState()>3) {
                    ComRecruitersModel com = comRecruitersService.getComRecruitersById(user.getRId());
                    com.setEnterprise(enterpriseService.findModelById(com.getComId()));
                    user.setRealName(com.getRealName());
                    hrLoginMak(com);//记录HR登录时间
                }

            }
        } else {
            user = new UserModel();
            user.setUserName(mobile);
            user.setMobile(mobile);
            user.setCrtTime(CommonHelp.getNowTimestamp().toString());
            user.setCRegisterState(0);
            if (type == 1) {
                //如果是首次登录，设置默认头像
                user.setFaceUrl(SystemConstant.DEFAULT_FACE_URL);
                CustomerModel customer = new CustomerModel();
//                customer.setRealName(mobile);
                customer.setJobStatus(0);
                int cusId = customerService.insert(customer);
                user.setCId(cusId);
                user.setRId(0);
                user.setCRegisterState(0);
                user.setRRegisterState(0);
                user.setRealName(customer.getRealName());
                user.setOpenid(openid);
                insert(user);
                if (customer.getJobStatus() == 1) {
                    user.setJobStatusText("离职-随时到岗");
                } else if (customer.getJobStatus() == 2) {
                    user.setJobStatusText("在职-月内到岗");
                } else if (customer.getJobStatus() == 3) {
                    user.setJobStatusText("在职-考虑机会");
                } else if (customer.getJobStatus() == 4) {
                    user.setJobStatusText("在职-暂不考虑");
                }else{
                    user.setJobStatusText("暂无状态");
                }
            } else if (type == 2) {

                user.setCrtTime(CommonHelp.getNowTimestamp().toString());
                user.setRRegisterState(0);
                user.setCId(0);
                user.setOpenid(openid);
                insert(user);

            }
            loginVo.setToken(token);
            user.setInfoStatus(user.getCRegisterState());
            user.setAuthenticationStatus(user.getRRegisterState());
            UserModel userModel = new UserModel();
            userModel.setRealName(user.getRealName());
            userModel.setFaceUrl(user.getFaceUrl());
            userModel.setMobile(user.getMobile());
            userModel.setId(user.getId());
            userModel.setLivePower(user.getLivePower());
            if(type==1)
            {
                userModel.setResumeStatus(user.getUserMsg());
                userModel.setInfoStatus(user.getInfoStatus());
                userModel.setJobStatusText(user.getJobStatusText());
            }else {
                userModel.setAuthenticationStatus(user.getAuthenticationStatus());
                if(StringTool.isNotEmpty(user.getRemarks()))
                {
                    userModel.setRemarks(user.getRemarks());
                }
            }
            loginVo.setUser(userModel);
            return Result.success(loginVo);
        }
        loginVo.setToken(token);
        user.setInfoStatus(user.getCRegisterState());
        user.setAuthenticationStatus(user.getRRegisterState());
        UserModel userModel = new UserModel();
        userModel.setRealName(user.getRealName());
        userModel.setFaceUrl(user.getFaceUrl());
        userModel.setMobile(user.getMobile());
        userModel.setId(user.getId());
        userModel.setLivePower(user.getLivePower());
        if(type==1)
        {
            userModel.setResumeStatus(user.getUserMsg());
            userModel.setInfoStatus(user.getInfoStatus());
            userModel.setJobStatusText(user.getJobStatusText());
        }else {
            userModel.setAuthenticationStatus(user.getAuthenticationStatus());

            if(user.getRId()!=null&&user.getRId()>0)
            {
                ComRecruitersModel cus = comRecruitersService.getComRecruitersById(user.getRId());
                EnterpriseModel enterpriseModel = enterpriseService.findModelById(cus.getComId());
                if(enterpriseModel!=null)
                {
                    if(StringTool.isNotEmpty(enterpriseModel.getWelfare()))
                    {
                        userModel.setComStatus(1);
                    }else {
                        userModel.setComStatus(2);
                    }
                }
            }else{
                userModel.setComStatus(2);
            }

            if(StringTool.isNotEmpty(user.getRemarks()))
            {
                userModel.setRemarks(user.getRemarks());
            }
        }
        loginVo.setUser(userModel);
        return Result.success(loginVo);
    }

    private void hrLoginMak(ComRecruitersModel com)
    {
        com.setLoginTime(CommonHelp.getNowTimestamp().toString());
        comRecruitersService.update(com);
    }

    @Override
    public Object getUserInfo(int type,UserModel user) {
        UserModel userModel = new UserModel();
        if (type == 1) {
            CustomerModel cus = customerService.getCustomerById(user.getCId());
            userModel.setRealName(cus.getRealName());
            userModel.setFaceUrl(user.getFaceUrl());
            userModel.setMobile(user.getMobile());
            userModel.setResumeStatus(userData(cus));
            userModel.setInfoStatus(user.getCRegisterState());
            userModel.setId(user.getId());
            userModel.setLivePower(user.getLivePower());
            if (cus.getJobStatus() == 1) {
                userModel.setJobStatusText("离职-随时到岗");
            } else if (cus.getJobStatus() == 2) {
                userModel.setJobStatusText("在职-月内到岗");
            } else if (cus.getJobStatus() == 3) {
                userModel.setJobStatusText("在职-考虑机会");
            } else if (cus.getJobStatus() == 4) {
                userModel.setJobStatusText("在职-暂不考虑");
            }else{
                userModel.setJobStatusText("暂无状态");
            }
        }else{
            if(user.getRId()!=null)
            {
                ComRecruitersModel com = comRecruitersService.getComRecruitersById(user.getRId());
                userModel.setRealName(com.getRealName());
                userModel.setFaceUrl(user.getFaceUrl());
                userModel.setMobile(user.getMobile());
                userModel.setAuthenticationStatus(user.getRRegisterState());
                userModel.setLivePower(user.getLivePower());
                userModel.setRemarks(user.getRemarks());
                if(user.getRRegisterState()==3)
                {
                    userModel.setRRegisterStateText("待审核");
                }else if(user.getRRegisterState()==4){
                    userModel.setRRegisterStateText("未通过");
                }else if(user.getRRegisterState()==9){
                    userModel.setRRegisterStateText("已通过");
            }

        }
            if(user.getRId()!=null)
            {
                ComRecruitersModel cus = comRecruitersService.getComRecruitersById(user.getRId());
                EnterpriseModel enterpriseModel = enterpriseService.findModelById(cus.getComId());
                if(enterpriseModel!=null)
                {
                    if(enterpriseModel.getScaleId()!=null&&enterpriseModel.getScaleId()>0)
                    {
                        userModel.setComStatus(1);
                    }else {
                        userModel.setComStatus(2);
                    }
                }
            }



        }
        return userModel;
    }

    @Override
    public int getNosUserCount() {
        QueryWrapper<UserModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("r_register_state",3);
        return userMapper.selectCount(queryWrapper);
    }

    @Override
    public int getNosRegisterCount() {
        QueryWrapper<UserModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.gt("r_register_state",0);
        queryWrapper.lt("r_register_state",9);
        return userMapper.selectCount(queryWrapper);
    }

    public int userData(CustomerModel customer) {

        if (customer.getBirthday() == null) {
            return 0;
        }
        List<JobIntentionModel> intentList = jobIntentionService.getIntentionListByCustomerId(customer.getId());
        if (intentList == null || intentList.size() <= 0) {
            return 0;
        }

        return 1;
    }
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    public static String getOpenid(String code) {
        //请求封装参数
        Map<String, String> map = new HashMap<>();
        map.put("appid", WXConstant.APPID);
        map.put("secret", WXConstant.SECRET);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        JSONObject jsonObject = JSON.parseObject(json);
        return jsonObject.getString("openid");
    }
}
